<template>
  <div class="area">
    <div class="avatar-area">
      <van-uploader
          :multiple="false"
          :max-count="1"
          v-model="state.fileList"
          lazy-load
          :after-read="afterReadByHeadImg"
          :before-delete="beforeDelete" />
    </div>
    <div class="btn">更新</div>
  </div>
</template>
<script setup lang="ts">
import {useRoute, useRouter} from "vue-router";
import {useMainStore} from "@/store";
import {onMounted, reactive} from "vue";
import {deleteImage, uploadImage} from "@/api/common";
import Compressor from "compressorjs";

const imgUrl = import.meta.env.VITE_IMG_URL;
const route = useRoute();
const router = useRouter();
const mainStore = useMainStore();

const state = reactive<any>({
  fileList: [],
  head_img_url: [],
});

onMounted(() => {
  let imgs = [];
  imgs.push({
    url : mainStore.userInfo.head_img_url
  })
  state.fileList = imgs;
});

const uploadRequestFunc = (file:any) => {
  return new Promise((resolve, reject) => {
    // compressorjs 默认开启 checkOrientation 选项
    // 会将图片修正为正确方向
    new Compressor(file, {
      quality: 0.4,
      success(result) {
        let files = new File([result], file.name, { type: file.type })
        resolve(files)
      },
      error(err) {
        console.log(err.message);
        reject(err);
      },
    });
  });
};

const afterReadByHeadImg = async (file: any, { index }: any) => {
  let newFile = await uploadRequestFunc(file.file)
  const res = await uploadImage(newFile);
  state.head_img_url[index].url2 = res.data;
};

// 删除图片
const beforeDelete = async (file: any): Promise<boolean> => {
  await deleteImage(file.url2);
  return true;
};
</script>
<style lang="scss" scoped>
.area {
  text-align: center;

  .btn {
    display: inline-block;
    width: 100px;
    height: 30px;
    text-align: center;
    line-height: 30px;
    color: white;
    border-radius: 50px;
    font-size: 14px;
    margin-top: 20px;
    border: none;
    background: linear-gradient(91deg, #f53d7d, #fb56b3);
  }
  .avatar-area {
    display: flex;
    flex-direction: row;
    justify-content: center;
    margin-top: 20px;
  }
}
</style>